package com.yellow.cloud.security.config;

import com.yellowframework.cloud.common.autoconfigure.CommonProperties;
import com.yellowframework.cloud.common.model.response.CommonCode;
import com.yellowframework.cloud.common.model.response.ResponseResult;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
@Order(-1)
class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(WebSecurity web) {
        web.ignoring().antMatchers(CommonProperties.path.getAnon().toArray(new String[]{}));

    }
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        AuthenticationManager manager = super.authenticationManagerBean();
        return manager;
    }

    //采用bcrypt对密码进行编码
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
            // 禁用session
            .csrf().disable()
            // 禁用表单登录
            .formLogin().disable()
            // 禁用匿名登录
            .anonymous().disable()

            // 接口授权 所有请求都需认证
            .authorizeRequests().anyRequest().authenticated()

            // 异常处理
            .and().exceptionHandling()
            // 认证的异常处理
            .authenticationEntryPoint((request, response, e) -> ResponseResult.output(response, CommonCode.UNAUTHENTICATED))
            // 授权的异常处理
            .accessDeniedHandler((request, response, e) -> ResponseResult.output(response, CommonCode.UNAUTHORISE))
            .and().httpBasic();
    }
}
